<?php

if (!defined('BASEPATH')) {
  exit('No direct script access allowed');
}

class Tweets_load_more extends AUTH_Controller {

  public function index() {

    if ($this->is_post() && $this->is_ajax()) {

      $type = $this->input->post('tweet_type', TRUE);
      $offset = (int) $this->input->post('tweet_offset', TRUE);

      // Search term
      $search_term = $this->sanitize($this->input->post('search_term', TRUE));

      // Getting selected list
      $get_tweets = $this->get_tweets($type, $offset, $search_term);
      $tweets = $get_tweets['tweets'];
      $tweets_count = $get_tweets['tweets_count'];

      $tweet_data = array();
      if (!empty($tweets)) {
        foreach ($tweets as $tweet) {
          $html_data = array();
          $view_data['tweet'] = $tweet;
          $html_data['tweet_html'] = trim($this->load->view('tweets_load_more', $view_data, TRUE));
          $html_data['tweet_id'] = $tweet['tweet_id'];
          $tweet_data[] = $html_data;
        }
      }

      $has_more = 0;
      $get_tweets_more = $this->get_tweets($type, $offset + 10, $search_term);
      if (!empty($get_tweets_more['tweets'])) {
        $has_more = 1;
      }

      die(json_encode(array('status' => 1, 'data' => $tweet_data, 'has_more' => $has_more)));
    }

    redirect();
  }

  private function get_tweets($type = NULL, $offset = NULL, $search_term = NULL) {
    if ($type == 'top') {
      $get_tweets = $this->tweet_model->get_top_tweets(10, $offset);
      $get_tweets_count = $this->tweet_model->get_top_tweets_count(NULL);
      $tweets = $get_tweets['result'];
    } elseif ($type == 'my') {
      $get_tweets = $this->tweet_model->get_my_tweets($this->current_user['user_id'], 10, $offset);
      $get_tweets_count = $this->tweet_model->get_my_tweets_count($this->current_user['user_id'], NULL);
      $tweets = $get_tweets['result'];
    } elseif ($type == 'new') {
      $get_tweets = $this->tweet_model->get_tweets(10, $offset);
      $get_tweets_count = $this->tweet_model->get_tweets_count(NULL);
      $tweets = $get_tweets['result'];
    } elseif ($type == 'search' && !empty($search_term)) {
      $get_tweets = $this->tweet_model->search_tweets($search_term, 10, $offset);
      $get_tweets_count = $this->tweet_model->search_tweets_count($search_term, NULL);
      $tweets = $get_tweets['result'];
    } else {
      $type = 'active';
      $get_tweets = $this->tweet_model->get_active_tweets(10, $offset);
      $get_tweets_count = $this->tweet_model->get_active_tweets_count(NULL);
      $tweets = $get_tweets['result'];
    }
    return array('tweets' => $tweets, 'tweets_count' => $get_tweets_count);
  }

}

?>